//
//  WordMO.m
//  Words
//
//  Created by Mathieu on 8/06/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "WordMO.h"
#import "DictionaryMO.h"
#import "Blob.h"
#import "WordsAppDelegate.h"
@implementation WordMO

#pragma mark Initialisers
- (void)awakeFromInsert {
	[self setValue:[NSDate date] forKey:@"createdOn"];
	//make sure all languages know where they came from
	[self setIsDefined:NO];
}
//
//-(NSData *)dashboard{
//	NSData *stringData;
//	if ( textBlobCache == nil ){
//		stringData = [self valueForKey:@"textBlobData"];
//		if(stringData != nil){
//			textBlobCache = [[NSKeyedUnarchiver unarchiveObjectWithData:stringData] retain];
//		}
//	}
//	return textBlobCache;
//}
//
-(void)setDashboardData:(NSData *)newDashboard{

	NSLog(@"Unpacking dashboard");
	[self setPrimitiveValue:newDashboard forKey:@"dashboardData"];
	[self unpackBlobFromWord];
	

		//
//		//cache and archive in managedObject.
//		textBlobCache = [newTextBlob retain];
//		NSData *textBlobData = [NSKeyedArchiver archivedDataWithRootObject:newTextBlob];
//		[self setValue:textBlobData forKey:@"textBlobData"];
}

-(void)unpackBlobFromWord{	
	NSData *dashboardData = [self valueForKey:@"dashboardData"];
	NSMutableDictionary *theDict = [NSKeyedUnarchiver unarchiveObjectWithData:dashboardData];
	
	NSEnumerator *e = [theDict keyEnumerator];
	NSString *key;
	while(key = [e nextObject]){
		Blob *newBlob = [NSEntityDescription insertNewObjectForEntityForName:@"Blob" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
		NSManagedObjectID *theDictID = [[[self managedObjectContext] persistentStoreCoordinator] managedObjectIDForURIRepresentation:[NSURL URLWithString:key]];
		id dict = [[self managedObjectContext] objectWithID:theDictID];
		NSString *targetLang = [dict valueForKey:@"targetLanguages"]; //there's actually only ever one
		NSAttributedString *theBlobAtLast = [theDict objectForKey:key];
		[newBlob setTextBlob:theBlobAtLast];
		[newBlob setValue:targetLang forKey:@"capabilityKey"];
		[newBlob setValue:self forKey:@"word"];
	}
}


- (bool)isDefined {
	NSNumber *yes = [NSNumber numberWithBool:YES];
	if([[self valueForKey:@"isDef"] isEqualToNumber:yes]){
		return YES;
	}else{
		return NO;
	}
}

- (void)setIsDefined:(bool)value {
	//[self willChangeValueForKey:@"isDefined"];
	[self setValue:[NSNumber numberWithBool:value] forKey:@"isDef"];
//[self didChangeValueForKey:@"isDefined"];
}



/**
Creates a copy of this Word object in the specified context and store.  
 This is used to copy instances from one store to another (since we cannot 
create cross-store relationships.)
 */

- (WWManagedObject *) copyToContext: (NSManagedObjectContext *)context andStore:(id)store {
	
    // insert a new Word first
    WordMO *newWord = [NSEntityDescription insertNewObjectForEntityForName:@"Word" inManagedObjectContext:context];
    if ( store ) {
        [context assignObject:newWord toPersistentStore:store];
    }
    
    // use API on the base class to copy the properties
    [newWord copyAttributesFromObject: self];
	
    // copy the definitions, exampleSentences, and language.  note that we want to always create
    // new definition and example sentence copies, but will use existing languages
    [newWord copyToOneRelationshipForKey: @"language" fromObject:self useExisting:NO];
    [newWord copyToManyRelationshipForKey: @"definitions" fromObject:self useExisting:YES];
    [newWord copyToManyRelationshipForKey: @"exampleSentences" fromObject:self useExisting:YES];
    
    // return
    return newWord;
}


// adds a definition to this array with simple strings
- (void)addDefinitionWithLocalString:(NSString *)local andForeignString:(NSString *)foreign{
	//set up the new entity
	NSManagedObject *newDefinition = [NSEntityDescription insertNewObjectForEntityForName:@"Definition" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
	[newDefinition setValue:local forKey:@"local"];
	[newDefinition setValue:foreign forKey:@"foreign"];
	//use convenience method in WWManagedObject to add to the many relationship
	[self addObject:newDefinition toToManyRelationshipForKey:@"definitions"];
}




#pragma mark Instance Methods
- (void)incrementTimesSeen{
	int oldNumber = [[self valueForKey:@"timesEncountered"] intValue];
	NSNumber *newNumber = [NSNumber numberWithInt:(oldNumber + 1)];

	[self setValue:newNumber forKey:@"timesEncountered"];
}

#pragma mark Archiving Support
- (void)encodeWithCoder:(NSCoder *)coder
{
	[coder encodeObject:[self valueForKey:@"createdOn"] forKey:@"WCreatedOn"];
	[coder encodeObject:[self valueForKey:@"isDef"] forKey:@"WIsDef"];
	[coder encodeObject:[self valueForKey:@"known"] forKey:@"WKnown"];
	[coder encodeObject:[self valueForKey:@"lastQuizzed"] forKey:@"WLastQuizzed"];
	[coder encodeObject:[self valueForKey:@"mainDef"] forKey:@"WMainDef"];
	[coder encodeObject:[self valueForKey:@"maybeKnown"] forKey:@"WMaybeKnown"];
	[coder encodeObject:[self valueForKey:@"secondaryDef"] forKey:@"WSecondaryDef"];
	[coder encodeObject:[self valueForKey:@"textBlobData"] forKey:@"WTextBlobData"];
	[coder encodeObject:[self valueForKey:@"timesEncountered"] forKey:@"WTimesEncountered"];
	[coder encodeObject:[self valueForKey:@"word"] forKey:@"WWord"];
	[coder encodeObject:[self valueForKey:@"wordType"] forKey:@"WWordType"];
    return;
}

-(int)numberOfDefsForKey:(NSString *)key{
	NSSet *defs = [self mutableSetValueForKey:@"definitions"];
	NSPredicate *pred = [NSPredicate predicateWithFormat:@"capabilityKey == %@", key];
	NSArray *allDefsArray = [defs allObjects];
	NSArray *filteredArray = [allDefsArray filteredArrayUsingPredicate:pred];
	return [filteredArray count];
}

- (id)initWithCoder:(NSCoder *)coder
{
	WordMO *word = [NSEntityDescription insertNewObjectForEntityForName:@"Word" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
	[word setValue:[coder decodeObjectForKey:@"WCreatedOn"] forKey:@"createdOn"];
	[word setValue:[coder decodeObjectForKey:@"WIsDef"] forKey:@"isDef"];
	[word setValue:[coder decodeObjectForKey:@"WKnown"] forKey:@"known"];    
	[word setValue:[coder decodeObjectForKey:@"WLastQuizzed"] forKey:@"lastQuizzed"];    
	[word setValue:[coder decodeObjectForKey:@"WMainDef"] forKey:@"mainDef"];    
	[word setValue:[coder decodeObjectForKey:@"WMaybeKnown"] forKey:@"maybeKnown"];    
	[word setValue:[coder decodeObjectForKey:@"WSecondaryDef"] forKey:@"secondaryDef"];    
	[word setValue:[coder decodeObjectForKey:@"WTextBlobData"] forKey:@"textBlobData"];    
	[word setValue:[coder decodeObjectForKey:@"WTimesEncountered"] forKey:@"timesEncountered"];    
	[word setValue:[coder decodeObjectForKey:@"WWord"] forKey:@"word"];    
	[word setValue:[coder decodeObjectForKey:@"WWordType"] forKey:@"wordType"];    
	return word;
}

@end
